package com.rightrule.rule.fieldtask;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rightrule.rule.constans.CommonConstant;
import com.rightrule.rule.dto.FieldComputeTask;
import groovy.lang.GroovyObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ScriptTaskService implements ComputingTaskService {

    /**
     * 脚本类字段结果
     *
     * @param task
     * @return
     */
    @Override
    public JSONObject getResult(FieldComputeTask task) {
        log.info("script task begin execute,task={}", task);

        try {
            String reqParams = task.getReqParams();
            // todo 待完善
//            reqParams = TaskServerUtils.parsePlaceHolder(reqParams, task);
            JSONArray reqArray = JSONArray.parseArray(reqParams);
            Object[] objects = reqArray.toArray();
            Class groovyClass = (Class) task.getGroovyClass();
            GroovyObject instance = (GroovyObject) groovyClass.newInstance();
            Object invokeResult = instance.invokeMethod(CommonConstant.SCRIPT_MAIN_METHOD, objects);
            return (JSONObject) JSONObject.toJSON(invokeResult);
//            TaskServerUtils.returnJSONObject(invokeResult)
        } catch (Exception e) {
            // todo 抛业务异常
        }
        return null;
    }
}
